/*TODO :
Supprimer les startActivityForResult, le onclickitemlist modifie directement le champ, 
le champ est stocké dans LlianeGlobal
 */
package com.llianejapan;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;

import com.llianejapan.ImeDo.ImeWV;
import com.llianejapan.Quizz.QuizzL;
import com.llianejapan.Quizz.QuizzQ;
import com.llianejapan.RomaTo.RomaToHK;
import com.llianejapan.RomaTo.RomaToKanji;
import com.llianejapan.ToRoma.HKToRoma;
import com.llianejapan.ToRoma.KanjiToRoma;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class LlianeJapan extends TabActivity {
	/** Called when the activity is first created. */		
	public String translator_answer;
	TabHost mTabHost;
	Context context;

	RomaToKanji roma2kanji_translator;

	//Romaji to Hiragana
	Button roma2hk_button;
	Button roma2hk_button_c;
	TextView roma2hk_showHK;
	EditText roma2hk_editHK;

	//Hiragana to Romaji
	Button hk2roma_button;
	Button hk2roma_button_c;
	ImageButton hk2roma_color_b;

	//Romaji to Kanji
	Button roma2kanji_button;
	Button roma2kanji_button_c;
	Button roma2kanji_zoom;


	//Kanji to Romaji
	Button kanji2roma_button;
	Button kanji2roma_button_c;
	ImageButton kanji2roma_color_b;

	//English2Japanese
	Button ime_hira_b;
	Button ime_kata_b;
	Button ime_kanji_b;
	Button ime_hotlink_b;
	Button ime_copy_b;	

	//Quizz
	Button quizz_download;
	Button quizz_refresh;
	Button quizz_go;

	Canvas hira2roma_cvs;
	Canvas kata2roma_cvs;
	Canvas kanji2roma_cvs;

	public int oldX = -1;
	public int oldY = -1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		//Local variables
		super.onCreate(savedInstanceState);
		
		//Loading Preferences
		final SharedPreferences settings = getSharedPreferences("LlianeJapan", 0);
	    
		setTheme(android.R.style.Theme_Black_NoTitleBar);
		setContentView(R.layout.main);			
		
	
		mTabHost = getTabHost();
		
		//Paint dessin
		final Paint hk_paint = new Paint();
		hk_paint.setStrokeCap(Paint.Cap.ROUND);
		hk_paint.setStrokeWidth(14);
		hk_paint.setColor(Color.BLACK);
		final Paint kanji_paint = new Paint();
		kanji_paint.setStrokeCap(Paint.Cap.ROUND);
		kanji_paint.setStrokeWidth(14);
		kanji_paint.setColor(Color.BLACK);

		LlianeGlobal.appfpath = getFilesDir().getPath();

		//Romaji to Kanji Translator
		roma2kanji_translator = new RomaToKanji ();

		//TabWidget lolw = (TabWidget) findViewById(R.id.)
		//Hiragana Tab
		mTabHost.addTab(mTabHost.newTabSpec("tab_hiragana").setIndicator(getString(R.string.tab_hk)).setContent(R.id.tabHK));    
		//Romaji to Hiragana
		LlianeGlobal.radio_hira = (RadioButton) findViewById(R.id.radio_hira);
		LlianeGlobal.radio_kata = (RadioButton) findViewById(R.id.radio_kata);
		LlianeGlobal.radio_hira.setChecked(true);
		roma2hk_button = (Button) findViewById(R.id.roma_to_hk);
		roma2hk_button_c = (Button) findViewById(R.id.roma_to_hk_c);
		roma2hk_showHK = (TextView) findViewById(R.id.showHK);
		roma2hk_editHK = (EditText) findViewById(R.id.editHK);
		roma2hk_button_c.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				roma2hk_editHK.setText("");
				roma2hk_showHK.setText("");
				roma2hk_showHK.setTextSize(15);    		
			}
		});
		roma2hk_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				roma2hk_showHK.setText(RomaToHK.roma2hk(roma2hk_editHK.getText()));
				roma2hk_showHK.setTextSize(RomaToHK.font_size);
			}
		});    
		//Hiragana to Romaji
		hk2roma_color_b = (ImageButton) findViewById(R.id.hk_color_b);
		hk2roma_color_b.setImageResource(R.drawable.dot_black);
		hk2roma_button = (Button) findViewById(R.id.hk_to_roma);
		hk2roma_button_c = (Button) findViewById(R.id.hk_to_roma_c);
		LlianeGlobal.hk2roma_showRoma1 = (TextView) findViewById(R.id.showRoma1);
		LlianeGlobal.hk2roma_drawHK = (ImageView) findViewById(R.id.drawHK);
		if (LlianeGlobal.hk2roma_bmpHK == null)
		{
			LlianeGlobal.hk2roma_strokes = 0;
			LlianeGlobal.hk2roma_bmpHK = Bitmap.createBitmap(320, 200, Bitmap.Config.ARGB_8888);
			for (int x = 0; x < 320; x++)
				for (int y = 0; y < 200; y++)
					LlianeGlobal.hk2roma_bmpHK.setPixel(x, y, Color.WHITE);
		}
		LlianeGlobal.hk2roma_drawHK.setImageBitmap(LlianeGlobal.hk2roma_bmpHK);

		hk2roma_color_b.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				if (hk_paint.getColor() == Color.BLACK){
					hk_paint.setColor(Color.WHITE);
					hk2roma_color_b.setImageResource(R.drawable.dot_white);
				}
				else
				{
					hk_paint.setColor(Color.BLACK);
					hk2roma_color_b.setImageResource(R.drawable.dot_black);
				}			
			}    	
		});
		LlianeGlobal.hk2roma_drawHK.setOnTouchListener(new OnTouchListener () {
			public boolean onTouch(View v, MotionEvent event) {  
				hira2roma_cvs = new Canvas(LlianeGlobal.hk2roma_bmpHK);	
				if (event.getAction() != MotionEvent.ACTION_DOWN)
					hira2roma_cvs.drawLine(event.getX(), event.getY(), oldX, oldY, hk_paint);
				else
					LlianeGlobal.hk2roma_strokes++;
				oldX = (int) event.getX();
				oldY = (int) event.getY();
				LlianeGlobal.hk2roma_drawHK.setImageBitmap(LlianeGlobal.hk2roma_bmpHK);
				return true;
			}    	
		});
		hk2roma_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				Intent intent = new Intent();    		
				intent.setClass(LlianeJapan.this, HKToRoma.class);    		
				startActivity(intent);
			}
		});

		hk2roma_button_c.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.hk2roma_strokes = 0;
				LlianeGlobal.hk2roma_showRoma1.setText("");
				for (int x = 0; x < 320; x++)
					for (int y = 0; y < 200; y++)
						LlianeGlobal.hk2roma_bmpHK.setPixel(x, y, Color.WHITE);
				LlianeGlobal.hk2roma_drawHK.setImageBitmap(LlianeGlobal.hk2roma_bmpHK);
				oldX = oldY = -1;
			}
		});    



		//Kanji Tab
		mTabHost.addTab(mTabHost.newTabSpec("tab_kanji").setIndicator(getString(R.string.tab_kanji)).setContent(R.id.tabKanji));
		//Romaji to Kanji
		roma2kanji_button = (Button) findViewById(R.id.roma_to_kanji);
		roma2kanji_button_c = (Button) findViewById(R.id.roma_to_kanji_c);
		roma2kanji_zoom = (Button) findViewById(R.id.roma_to_kanji_zoom);
		LlianeGlobal.roma2kanji_showKanji = (TextView) findViewById(R.id.showKanji);
		LlianeGlobal.roma2kanji_editKanji = (EditText) findViewById(R.id.editKanji);
		roma2kanji_button_c.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.roma2kanji_showKanji.setText("");
				LlianeGlobal.roma2kanji_editKanji.setText("");
			}
		}); 
		roma2kanji_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.stringBuffer = LlianeGlobal.roma2kanji_editKanji.getText().toString();
				Intent intent = new Intent();    		
				intent.setClass(LlianeJapan.this, RomaToKanji.class);
				RomaToKanji.forTranslate = 0;
				startActivity(intent);
			}
		});  
		roma2kanji_zoom.setOnLongClickListener(new Button.OnLongClickListener() {
			public boolean onLongClick(View v){
				Bitmap kanji_bmp = Bitmap.createBitmap(320, 200, Bitmap.Config.ARGB_8888);
				Canvas kanji_cvs = new Canvas(kanji_bmp);        	
				Paint kanji_paint = new Paint();        

				kanji_cvs.drawColor(Color.WHITE);
				kanji_paint.setStyle(Paint.Style.FILL);
				kanji_paint.setAntiAlias(true);
				kanji_paint.setColor(Color.BLACK);
				kanji_paint.setTextSize(180);
				kanji_paint.setTextAlign(Paint.Align.CENTER);
				kanji_cvs.drawText(LlianeGlobal.roma2kanji_showKanji.getText().toString(), 160, 160, kanji_paint);
				LlianeGlobal.kanji2roma_bmpKanji = kanji_bmp;	
				LlianeGlobal.kanji2roma_drawKanji.setImageBitmap(LlianeGlobal.kanji2roma_bmpKanji);
				return true;
			}	
		});
		roma2kanji_zoom.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				Intent intent = new Intent();    		
				intent.setClass(LlianeJapan.this, WV.class);    		
				startActivity(intent); 
			}
		});
		//Kanji to Romaji
		kanji2roma_button = (Button) findViewById(R.id.kanji_to_roma);
		kanji2roma_button_c = (Button) findViewById(R.id.kanji_to_roma_c);
		kanji2roma_color_b = (ImageButton) findViewById(R.id.kanji_color_b);
		kanji2roma_color_b.setImageResource(R.drawable.dot_black);
		LlianeGlobal.kanji2roma_showRoma3 = (TextView) findViewById(R.id.showRoma3);
		LlianeGlobal.kanji2roma_drawKanji = (ImageView) findViewById(R.id.drawKanji);
		if (LlianeGlobal.kanji2roma_bmpKanji == null)
		{
			LlianeGlobal.kanji2roma_strokes = 0;
			LlianeGlobal.kanji2roma_bmpKanji = Bitmap.createBitmap(320, 200, Bitmap.Config.ARGB_8888);
			for (int x = 0; x < 320; x++)
				for (int y = 0; y < 200; y++)
					LlianeGlobal.kanji2roma_bmpKanji.setPixel(x, y, Color.WHITE);
		}
		LlianeGlobal.kanji2roma_drawKanji.setImageBitmap(LlianeGlobal.kanji2roma_bmpKanji);
		LlianeGlobal.kanji2roma_drawKanji.setOnTouchListener(new OnTouchListener () {
			public boolean onTouch(View v, MotionEvent event) {
				kanji2roma_cvs = new Canvas(LlianeGlobal.kanji2roma_bmpKanji);				
				if (event.getAction() != MotionEvent.ACTION_DOWN)
					kanji2roma_cvs.drawLine(event.getX(), event.getY(), oldX, oldY, kanji_paint);
				else
					LlianeGlobal.kanji2roma_strokes++;
				oldX = (int) event.getX();
				oldY = (int) event.getY();
				LlianeGlobal.kanji2roma_drawKanji.setImageBitmap(LlianeGlobal.kanji2roma_bmpKanji);
				return true;
			}    	
		});
		kanji2roma_color_b.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				if (kanji_paint.getColor() == Color.BLACK){
					kanji_paint.setColor(Color.WHITE);
					kanji2roma_color_b.setImageResource(R.drawable.dot_white);
				}
				else
				{
					kanji_paint.setColor(Color.BLACK);
					kanji2roma_color_b.setImageResource(R.drawable.dot_black);
				}			
			}    	
		});
		kanji2roma_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				Intent intent = new Intent();    		
				intent.setClass(LlianeJapan.this, KanjiToRoma.class);    		
				startActivity(intent);   		
			}
		});
		kanji2roma_button_c.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.kanji2roma_strokes = 0;
				LlianeGlobal.kanji2roma_showRoma3.setText("");
				for (int x = 0; x < 320; x++)
					for (int y = 0; y < 200; y++)
						LlianeGlobal.kanji2roma_bmpKanji.setPixel(x, y, Color.WHITE);
				LlianeGlobal.kanji2roma_drawKanji.setImageBitmap(LlianeGlobal.kanji2roma_bmpKanji);
			}
		});

		//Translate Tab
		mTabHost.addTab(mTabHost.newTabSpec("tab_translate").setIndicator(getString(R.string.tab_ime)).setContent(R.id.tabTrans));
		//English to Japanese
		ime_hira_b = (Button) findViewById(R.id.ime_hira_b);
		ime_kata_b = (Button) findViewById(R.id.ime_kata_b);
		ime_kanji_b = (Button) findViewById(R.id.ime_kanji_b);
		ime_copy_b = (Button) findViewById(R.id.copy_b);
		LlianeGlobal.ime_1 = (EditText) findViewById(R.id.ime_1);
		LlianeGlobal.ime_2 = (EditText) findViewById(R.id.ime_2);
		ime_copy_b.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v){
				ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
				cb.setText(LlianeGlobal.ime_2.getText());
			}
		});
		ime_hira_b.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.radio_hira.setChecked(true);
				LlianeGlobal.ime_2.append(RomaToHK.roma2hk(LlianeGlobal.ime_1.getText()));
				LlianeGlobal.ime_1.setText("");
			}
		});
		ime_kata_b.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.radio_kata.setChecked(true);
				LlianeGlobal.ime_2.append(RomaToHK.roma2hk(LlianeGlobal.ime_1.getText()));
				LlianeGlobal.ime_1.setText("");
			}
		});
		ime_kanji_b.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				LlianeGlobal.stringBuffer = LlianeGlobal.ime_1.getText().toString();
				Intent intent = new Intent();    		
				intent.setClass(LlianeJapan.this, RomaToKanji.class);
				RomaToKanji.forTranslate = 1;
				startActivity(intent);				
			}
		});

		//QUIZZ TAB
		mTabHost.addTab(mTabHost.newTabSpec("tab_quizz").setIndicator(getString(R.string.tab_quizz)).setContent(R.id.tabQuizz));
		quizz_go = (Button) findViewById(R.id.quizz_go);
		quizz_download = (Button) findViewById(R.id.quizz_download);
		quizz_refresh = (Button) findViewById(R.id.quizz_refresh);

		LlianeGlobal.quizz_s_paths = new Vector<String>();
		LlianeGlobal.quizz_s = (Spinner) findViewById(R.id.quizz_s);
		LlianeGlobal.quizz_s_choices = 
			new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);		
		LlianeGlobal.quizz_s_choices.setDropDownViewResource(android.R.layout.simple_spinner_item);		
		LlianeGlobal.quizz_s.setAdapter(LlianeGlobal.quizz_s_choices);


		LlianeGlobal.quizz_d_paths = new Vector<String>();
		LlianeGlobal.quizz_d = (Spinner) findViewById(R.id.quizz_d);
		LlianeGlobal.quizz_d_choices = 
			new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);		
		LlianeGlobal.quizz_d_choices.setDropDownViewResource(android.R.layout.simple_spinner_item);
		LlianeGlobal.quizz_d.setAdapter(LlianeGlobal.quizz_d_choices);

		quizz_go.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				try {
					if (LlianeGlobal.quizz_s_paths.size() > 0)
					{
						QuizzL.is = new BufferedReader(new InputStreamReader
	                            (openFileInput(LlianeGlobal.quizz_s_paths.elementAt(
	    								(int) LlianeGlobal.quizz_s.getSelectedItemId())),
	    								"UTF8"));
						QuizzL.load();
						Intent intent = new Intent();    		
						intent.setClass(LlianeJapan.this, QuizzQ.class);
						startActivity(intent);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		});
		quizz_refresh.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				quizz_refresh();
			}
		});		
		quizz_download.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				try				
				{
					String filename = LlianeGlobal.quizz_d_paths.elementAt( 
							(int) LlianeGlobal.quizz_d.getSelectedItemId());
					  Log.e("LDEBUG1", filename);
					URL myURL = new URL(LlianeGlobal.QPath + filename);
					URLConnection conn = myURL.openConnection();
					conn.connect();
					BufferedReader is = new BufferedReader(new InputStreamReader
                            (conn.getInputStream(), "UTF8"));
					FileOutputStream fOut = openFileOutput(filename, MODE_WORLD_READABLE); 
					OutputStreamWriter osw = new OutputStreamWriter(fOut, "UTF8"); 
					String istr;
					while ((istr = is.readLine()) != null)
						osw.write(istr+"\n");
					osw.close();
					r_quizz_refresh();
				}
				catch (Exception e) {
				}
			}
		});
		r_quizz_refresh();

		mTabHost.addTab(mTabHost.newTabSpec("tab_help").setIndicator(getString(R.string.tab_help)).setContent(R.id.tabHelp));
		
		/* Notification for Lliane Light IME */
		final NotificationManager nm = (NotificationManager) getSystemService(  
				Context.NOTIFICATION_SERVICE);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 133743, 
				new Intent(this, ImeWV.class), 0);
		final Notification notify = new Notification(R.drawable.icon, 
				                                     getString(R.string.notification_cat),
				                                     System.currentTimeMillis());
		notify.setLatestEventInfo(this, 
				                  getString(R.string.notification_title),
				                  getString(R.string.notification_subtitle),
				                  contentIntent);
		
		LlianeGlobal.option_strokes = (CheckBox) findViewById(R.id.option_strokes);
		LlianeGlobal.option_notif = (CheckBox) findViewById(R.id.option_notif);
		LlianeGlobal.option_strokes.setChecked(settings.getBoolean("option_strokes", false));
		LlianeGlobal.option_notif.setChecked(settings.getBoolean("option_notif", true));
		if (!settings.getBoolean("option_notif", true))
			nm.cancel(133742);
		else
			nm.notify(133742, notify);
		
		LlianeGlobal.option_strokes.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				SharedPreferences.Editor settings_editor = settings.edit();
				settings_editor.putBoolean("option_strokes", isChecked);
				settings_editor.commit();
			}
		});
		LlianeGlobal.option_notif.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				if (isChecked)
					nm.notify(133742, notify);					
				else
					nm.cancel(133742);
					
				SharedPreferences.Editor settings_editor = settings.edit();
				settings_editor.putBoolean("option_notif", isChecked);
				settings_editor.commit();
			}
		});
		//nm.cancel(133742);
		
		mTabHost.setCurrentTab(0);
	}



	public void r_quizz_refresh()
	{	
		LlianeGlobal.quizz_s_choices.clear();
		LlianeGlobal.quizz_s_paths.clear();

		//Create a buffer file to prevent an error while listing files in a non-existant
		//Directory...
		try {
			FileOutputStream fOut = openFileOutput("buffer", MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 
			osw.write("empty");
			osw.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		String[] flist = getFilesDir().list();
		for (int j = 0; j < flist.length; j++)
		{
			if (flist[j].endsWith(".ljq"))
			{
				try {
					BufferedReader is = new BufferedReader(new InputStreamReader
                            (openFileInput(flist[j]),"UTF8"));
					LlianeGlobal.quizz_s_choices.add(is.readLine());
					LlianeGlobal.quizz_s_paths.add(flist[j]);
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		}
	}
	public void quizz_refresh()
	{
		try 
		{
			LlianeGlobal.quizz_d_choices.clear();
			LlianeGlobal.quizz_d_paths.clear();
			URL myURL = new URL(LlianeGlobal.QPath + "list.txt");
			URLConnection conn = myURL.openConnection();
			conn.connect();
			BufferedReader is = new BufferedReader(new InputStreamReader
                    (conn.getInputStream(),"UTF8"));
			String istr;
			while ((istr = is.readLine()) != null)
			{
			  LlianeGlobal.quizz_d_choices.add(istr);
			  istr = is.readLine();
			  LlianeGlobal.quizz_d_paths.add(istr);
			}
		}
		catch (Exception e) {
			// TODO: handle exception
		}
	}
}